package ezai

import (
	"gitee.com/hongzhaomin/ezai/bean"
	"gitee.com/hongzhaomin/hzm-common-go/concurrent"
	"sync"
)

// ChatSession 会话session接口
type ChatSession interface {

	// GetMessages 根据会话id获取消息列表
	GetMessages(sessionId string) []*bean.Message

	// AddMessage 根据会话id添加消息
	AddMessage(sessionId string, msg *bean.Message)

	// Clear 根据会话id清除消息
	Clear(sessionId string)
}

func NewCacheChatSession() *LocalCacheChatSession {
	return &LocalCacheChatSession{
		cacheMap: concurrent.NewMap[string, []*bean.Message](),
		mu:       new(sync.Mutex),
	}
}

var _ ChatSession = (*LocalCacheChatSession)(nil)

// LocalCacheChatSession 本地缓存会话session
type LocalCacheChatSession struct {
	cacheMap *concurrent.Map[string, []*bean.Message]
	mu       *sync.Mutex
}

func (my *LocalCacheChatSession) GetMessages(sessionId string) []*bean.Message {
	msgs, _ := my.cacheMap.Load(sessionId)
	return msgs
}

func (my *LocalCacheChatSession) AddMessage(sessionId string, msg *bean.Message) {
	if sessionId == "" {
		panic("sessionId can not be empty")
	}
	if msg == nil {
		panic("msg can not be nil")
	}
	my.mu.Lock()
	defer my.mu.Unlock()
	msgs, _ := my.cacheMap.Load(sessionId)
	msgs = append(msgs, msg)
	my.cacheMap.Store(sessionId, msgs)
}

func (my *LocalCacheChatSession) Clear(sessionId string) {
	my.cacheMap.Delete(sessionId)
}
